import React, {Component} from 'react';
import {Button, Card, Table, Typography, Modal, Tag, Radio, Form, Input, InputNumber, message, notification} from "antd";
import './style.less'
import XLSX from 'xlsx'
import moment from "moment";
import { addCarManager, getCarManager, editCarManager, deleteCarManager} from "../../api/carManager";

class Index extends Component {
    constructor(props){
        super(props);
        this.formRef = React.createRef();
        this.formEditRef = React.createRef();
        this.state = {
            total: 0,
            pageSize: 6,
            current: 1,
            pageSizeOptions: [6,8,10,12,14],
            loading: false,
            deleteName: '',
            confirmLoading: false,
            deleteIsVisible: false,
            deleteId: '',
            editIsVisible: false,
            editId: '',
            addIsVisible: false,
            dataSource: [],
            columns: [
                {
                    title: '管理员编号',
                    dataIndex: 'key',
                    key: 'key'
                },
                {
                    title: '姓名',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '管理范围',
                    dataIndex: 'position',
                    key: 'position',
                },
                {
                    title: '年龄',
                    dataIndex: 'age',
                    key: 'age',
                    render: (age) => {
                        let color = 'green';
                        if (age > 30){
                            color= 'red'
                        }
                        return <Tag color={color}>{age}</Tag>
                    }
                },
                {
                    title: '电话',
                    dataIndex: 'iphone',
                    key: 'iphone'
                },
                {
                    title: '身份证',
                    dataIndex: 'identity',
                    key: 'identity'
                },
                {
                    title: '操作',
                    key: 'action',
                    render: (text,record,index) => {
                        return <Radio.Group size='default'>
                            <Button value='mod' onClick={this.editManager.bind(this,record)} type='primary'>编辑</Button>
                            <Button value='delete' onClick={this.deleteManager.bind(this,{text,record,index})} type='error'>删除</Button>
                        </Radio.Group>;
                    }
                }
            ],
            layout: {
                labelCol: {
                    span: 6,
                },
                wrapperCol: { span: 12 },
            },
            tailLayout: {
                wrapperCol: { span: 6, offset: 6},
            }
        }
    }

    //导出汽车管理员excel表格
    /*
    *  导出excel表格，一般都是由后端处理了
    *  前端发送ajax请求数据，后端进行数据处理
    * */
    toExcel = () => {
        let carManagerExcel = [];
        const carManagerKeys = this.state.columns.slice(0,this.state.columns.length - 1).map(item => item.title);
        carManagerKeys.unshift('id');
        carManagerExcel.push(carManagerKeys)
        for (let i of this.state.dataSource){
            let {id, name, position,age, iphone, identity} = i;
            carManagerExcel.push([id, name, position,age, iphone, identity]);
        }
        if (this.state.columns.length === 0){
            notification.open({
                message: 'excel打印失败',
                description:
                    '暂时没有列表数据',
                onClick: () => {
                    console.log('点击事件');
                },
            });
            return ;
        }
        const ws = XLSX.utils.aoa_to_sheet(carManagerExcel);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
        XLSX.writeFile(wb, `carManagerList-${this.state.current}-${moment().format('YYYY-MM-DD h:mm:ss')}.xlsx`)
    }

    //添加汽车管理员
    addManager = () => {
        this.setState({
            addIsVisible: true
        })
    }

    //页码改变的回调
    paginationChange = (current,pageSize) => {
        this.setState({
            current,
            pageSize: pageSize
        })
    }

    //每页条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({
            current: 1,
            pageSize: size
        })
    }

    //取消删除
    deleteCancel = (e) => {
        this.setState({
            deleteId: '',
            deleteName: '',
            deleteIsVisible: false
        })
    }

    //确定删除
    deleteOk = (e) => {
        this.setState({
            confirmLoading: true
        })
        deleteCarManager({id: this.state.deleteId}).then(res => {
            message.success(res.msg);
            this.init()
        }).catch(err => {
            message.error('删除失败');
        }).finally(() => {
            this.setState({
                deleteId: '',
                deleteName: '',
                deleteIsVisible: false
            })
        })
    }

    //编辑汽车管理员信息
    editManager = (record) => {
        console.log(record)
        this.setState({
            editIsVisible: true,
            editId: record.key
        },() => {
            setTimeout(() => {
                this.formEditRef.current.setFieldsValue({
                    ...record
                })
            },0)
        })
    }

    //删除汽车管理员信息
    deleteManager = ({text,record,index}) => {
        this.setState({
            deleteId: record.key,
            deleteName: record.name,
            deleteIsVisible: true
        })
    }

    //添加取消
    addCancel = () => {
        this.setState({
            addIsVisible: false
        })
    }

    //添加确定
    addOk = () => {
        this.setState({
            confirmLoading: true
        })
        const data = this.formRef.current.getFieldsValue();
        addCarManager(data).then(res => {
            message.success(res.msg);
            this.formRef.current.setFieldsValue({
                name: '',
                position: "",
                age: '',
                iphone: '',
                identity: ''
            })
            this.init();
        }).catch(err => {
            this.setState({
                confirmLoading: false
            })
        }).finally(() => {
            this.setState({
                confirmLoading: false
            })
        })
    }
    //取消编辑
    editCancel = () => {
        this.setState({
            editIsVisible: false,
            editId: ''
        })
    }
    //保存编辑
    editOk = () => {
        this.setState({
            confirmLoading: true
        })
        const data = this.formEditRef.current.getFieldsValue();
        editCarManager({...data,id: this.state.editId}).then(res => {
            message.success(res.msg);
            this.init();
        }).catch(err => {
            this.setState({
                confirmLoading: false
            })
        }).finally(() => {
            this.setState({
                confirmLoading: false
            })
        })
    }


    //初始化数据
    init = () => {
        getCarManager().then(res => {
            const dataSource = res.data.map(item => {
                return {
                    key: item.id,
                    name: item.name,
                    position: item.position,
                    age: item.age,
                    iphone: item.iphone,
                    identity: item.identity
                }
            })
            this.setState({
                dataSource,
                total: res.data.length
            })
        })
    }

    componentDidMount() {
        this.init();
    }

    render() {
        return (
            <Card title="汽车管理员操作" className='mod_card' extra={<span><Button onClick={this.addManager} type='primary' style={{marginRight: 10}}>添加管理员</Button><Button type='primary' shape="round" onClick={this.toExcel}>Excel导出</Button></span>}>
                <Table
                    dataSource={this.state.dataSource}
                    columns={this.state.columns}
                    pagination={{
                        total: this.state.total,
                        pageSize: this.state.pageSize,
                        showSizeChanger: true,
                        pageSizeOptions: this.state.pageSizeOptions,
                        showQuickJumper: true,
                        current: this.state.current,
                        onChange: this.paginationChange,
                        onShowSizeChange: this.onShowSizeChange
                    }}
                    loading={this.state.loading}
                />
                <Modal
                    visible={this.state.addIsVisible}
                    title="添加管理员"
                    confirmLoading={this.state.confirmLoading}
                    maskClosable={false}
                    okText="确定添加"
                    cancelText="取消"
                    onCancel={this.addCancel}
                    onOk={this.addOk}
                >
                    <Form
                        {...this.state.layout}
                        name="add_car_manager"
                        className="add_car_manager"
                        ref={this.formRef}
                        initialValues={{ remember: true }}
                    >
                        <Form.Item
                            label="名字"
                            name="name"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="管理范围"
                            name="position"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="年龄"
                            name="age"
                        >
                            <InputNumber/>
                        </Form.Item>
                        <Form.Item
                            label="电话"
                            name="iphone"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="身份证"
                            name="identity"
                        >
                            <Input/>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal
                    visible={this.state.editIsVisible}
                    title="编辑"
                    confirmLoading={this.state.confirmLoading}
                    maskClosable={false}
                    okText="确定"
                    cancelText="取消"
                    onCancel={this.editCancel}
                    onOk={this.editOk}
                >
                    <Form
                        {...this.state.layout}
                        name="edit_car_manager"
                        className="edit_car_manager"
                        ref={this.formEditRef}
                        initialValues={{ remember: true }}
                    >
                        <Form.Item
                            label="名字"
                            name="name"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="管理范围"
                            name="position"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="年龄"
                            name="age"
                        >
                            <InputNumber/>
                        </Form.Item>
                        <Form.Item
                            label="电话"
                            name="iphone"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="身份证"
                            name="identity"
                        >
                            <Input/>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal
                    title='此操作不可逆，请谨慎操作！'
                    cancelText='取消删除'
                    confirmLoading={this.state.confirmLoading}
                    maskClosable={false}
                    okText='确定删除'
                    okType='primary'
                    visible={this.state.deleteIsVisible}
                    onCancel={this.deleteCancel}
                    onOk={this.deleteOk}
                >
                    <Typography>名字为“<span style={{color: "red",fontSize: '15px'}}>{this.state.deleteName}</span>"的汽车管理员信息</Typography>
                </Modal>
            </Card>
        );
    }
}

export default Index;